package com.bw.gmall.realtime.dws.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.bean.TradeProvinceOrderBean;
import com.bw.gmall.realtime.common.bean.TradeSkuOrderBean;
import com.bw.gmall.realtime.common.constant.Constant;
import com.bw.gmall.realtime.common.function.DimRichAsyncFunction;
import com.bw.gmall.realtime.common.function.DorisMapFunction;
import com.bw.gmall.realtime.common.util.DateFormatUtil;
import com.bw.gmall.realtime.common.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.table.utils.DateTimeUtils;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class DwsTradeProvinceOrderWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsTradeProvinceOrderWindow().start(10020, 4, Constant.TOPIC_DWD_TRADE_ORDER_DETAIL, Constant.DWS_TRADE_PROVINCE_ORDER_WINDOW+"1");
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> kafkaSource) {
        // 1.读取数据源
        // 2.清洗数据
        SingleOutputStreamOperator<JSONObject> etlStream = kafkaSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                try {
                    if (s != null) {
                        JSONObject jsonObject = JSON.parseObject(s);
                        String province_id = jsonObject.getString("province_id");
                        Long ts = jsonObject.getLong("ts");
                        if (province_id != null && ts != null) {
                            jsonObject.put("ts", ts * 1000);
                            collector.collect(jsonObject);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        // 3.添加水位线
        SingleOutputStreamOperator<JSONObject> watermarksStream = etlStream.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject jsonObject, long l) {
                return jsonObject.getLong("ts");
            }
        }));
        // 4.校正金额
        SingleOutputStreamOperator<TradeProvinceOrderBean> processStream = watermarksStream.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject jsonObject) throws Exception {
                return jsonObject.getString("id");
            }
        }).process(new KeyedProcessFunction<String, JSONObject, TradeProvinceOrderBean>() {

            private ValueState<BigDecimal> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<BigDecimal> stateDescriptor = new ValueStateDescriptor<>("splitTotalAmount", BigDecimal.class);
                stateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(Time.seconds(30L)).build());
                valueState = getRuntimeContext().getState(stateDescriptor);
            }

            @Override
            public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, TradeProvinceOrderBean>.Context context, Collector<TradeProvinceOrderBean> collector) throws Exception {
                BigDecimal splitTotalAmount = valueState.value();
                BigDecimal totalAmount = jsonObject.getBigDecimal("split_total_amount");
                String provinceId = jsonObject.getString("province_id");
                String orderId = jsonObject.getString("order_id");
                String Id = jsonObject.getString("id");
                Long ts = jsonObject.getLong("ts");
                splitTotalAmount = splitTotalAmount == null ? new BigDecimal(0) : splitTotalAmount;

                Set<String> orderIds = new HashSet<>();
                orderIds.add(orderId);
                collector.collect(TradeProvinceOrderBean.builder().orderAmount(totalAmount.subtract(splitTotalAmount)).provinceId(provinceId).orderIdSet(orderIds).orderDetailId(Id).ts(ts).build());
                // 更新状态数据
                valueState.update(totalAmount);
            }
        });
        // 5.分组 开窗 聚合
        SingleOutputStreamOperator<TradeProvinceOrderBean> reduceStream = processStream.keyBy(new KeySelector<TradeProvinceOrderBean, String>() {
            @Override
            public String getKey(TradeProvinceOrderBean tradeProvinceOrderBean) throws Exception {
                return tradeProvinceOrderBean.getProvinceId();
            }

            /*
                p_id   order_detail_id   orderIds    amount

                 1         1                set(10)        100
                 1         1                set(10)        80
                 1         2                set(10)        200
                 1         3                set(11)        200



             */
        }).window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10))).reduce(new ReduceFunction<TradeProvinceOrderBean>() {
            @Override
            public TradeProvinceOrderBean reduce(TradeProvinceOrderBean value1, TradeProvinceOrderBean value2) throws Exception {
                value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                value1.getOrderIdSet().addAll(value2.getOrderIdSet());
                return value1;
            }
        }, new ProcessWindowFunction<TradeProvinceOrderBean, TradeProvinceOrderBean, String, TimeWindow>() {
            @Override
            public void process(String s, ProcessWindowFunction<TradeProvinceOrderBean, TradeProvinceOrderBean, String, TimeWindow>.Context context, Iterable<TradeProvinceOrderBean> iterable, Collector<TradeProvinceOrderBean> collector) throws Exception {
                TimeWindow window = context.window();
                long start = window.getStart();
                long end = window.getEnd();
                for (TradeProvinceOrderBean tradeProvinceOrderBean : iterable) {
                    tradeProvinceOrderBean.setStt(DateFormatUtil.tsToDateTime(start));
                    tradeProvinceOrderBean.setEdt(DateFormatUtil.tsToDateTime(end));
                    tradeProvinceOrderBean.setCurDate(DateFormatUtil.tsToDate(System.currentTimeMillis()));
                    tradeProvinceOrderBean.setOrderCount((long) tradeProvinceOrderBean.getOrderIdSet().size());
                    collector.collect(tradeProvinceOrderBean);
                }
            }
        });
//        reduceStream.print();
        // 6.关联维度
        SingleOutputStreamOperator<TradeProvinceOrderBean> dimStreamByPro = AsyncDataStream.unorderedWait(reduceStream, new DimRichAsyncFunction<TradeProvinceOrderBean>() {
            @Override
            public String getTable() {
                return "dim_base_province";
            }

            @Override
            public String getRowKey(TradeProvinceOrderBean tradeProvinceOrderBean) {
                return tradeProvinceOrderBean.getProvinceId();
            }

            @Override
            public void setDimInfo(TradeProvinceOrderBean tradeProvinceOrderBean, JSONObject dimSkuInfo) {
                tradeProvinceOrderBean.setProvinceName(dimSkuInfo.getString("name"));
            }
        }, 60, TimeUnit.SECONDS);
        // 7.写入doris
//        dimStreamByPro.print();
        dimStreamByPro.map(new DorisMapFunction<>()).sinkTo(FlinkSinkUtil.getDorisSink(Constant.DWS_TRADE_PROVINCE_ORDER_WINDOW));
    }
}
